package com.zcily.demo.entity.dto;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Data
@Accessors(chain = true)
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    public static final int SUCCESS_CODE = 200;

    public static final int ERROR_CODE = 10000;

    private int code = SUCCESS_CODE;

    private String message;

    private T data;

    private long timestamp = System.currentTimeMillis();

    public Result() {
    }

    public Result(int code, T data, String message) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <S> Result<S> ok() {
        return new Result<>(SUCCESS_CODE, null, null);
    }

    public static <S> Result<S> ok(S data) {
        return new Result<>(SUCCESS_CODE, data, null);
    }

    public static Result<?> ok(String message) {
        return new Result<>(SUCCESS_CODE, null, message);
    }

    public static <S> Result<S> ok(S data, String message) {
        return new Result<>(SUCCESS_CODE, data, message);
    }

    public static <S> Result<S> error(int code) {
        if (code < ERROR_CODE) {
            throw new RuntimeException("不合法的code值");
        }
        return new Result<>(code, null, null);
    }

    public static <S> Result<S> error(String message) {
        return new Result<>(ERROR_CODE, null, message);
    }

    public static <S> Result<S> error(int code, String message) {
        if (code < ERROR_CODE) {
            throw new RuntimeException("不合法的code值");
        }
        return new Result<>(code, null, message);
    }
}
